<?php
/**
 * @brief Visabill支付插件类
 * @class Visabill
 * @package App
 * @subpackage  Driver.Payment
 * @author cjli
 */
class Visabill extends Payment implements Payment_Interface
{
	public function __construct()
	{
		$this->_paymentInfo = PaymentModel::get_payment_info('Visabill');
	}
	
  public function getSettingFields()
  {
    return array(
      'MerNo' => '商户帐号',
      'Signkey' => '商户密钥',
    	'GatewayNo' => '网关接入号',
    );
  }

  public function getSubmitForm($orderInfo)
  {
  	global $language_id;

    $languageInfo = SiteModel::get_language_info($language_id);
		 if ($languageInfo['code'] = "fr") {
			 $Language = 'FR';
		 }
		 else {
			 $Language = 'EN';
		 }

    $signkey = $this->_paymentInfo['config']['Signkey'];           //Signkey私钥
    $merNo = $this->_paymentInfo['config']['MerNo'];               //商户号
    $gatewayNo = $this->_paymentInfo['config']['GatewayNo'];       //网关接入号

	//$gateway = 'https://payment.secure-checkoutserver.com/Interface';
	//$gateway = url("/ownonlygateway.php");
	//$gateway = "https://".$_SERVER['HTTP_HOST']."/payment/visabill";
	$gateway = "https://".$_SERVER['HTTP_HOST']."/ownonlygateway.php";
    $paymentMethod = 'Credit Card';           //支付方式

    $orderNo = $orderInfo['order_sn'];            //订单号
		$firstName = $orderInfo['delivery_first_name'];
		$lastName = $orderInfo['delivery_last_name'];
		$email = $orderInfo['delivery_email'];
		$phone = $orderInfo['delivery_phone'];
		$country = $orderInfo['delivery_country'];
		//$country = 'fr';
		$state = $orderInfo['delivery_province'];
		$city = $orderInfo['delivery_city'];
		
		$address = $orderInfo['delivery_address'];
		$address .= $orderInfo['delivery_address2'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address2'] : null;
		$address .= $orderInfo['delivery_address3'] ? '&nbsp;&nbsp;'.$orderInfo['delivery_address3'] : null;

		$zip = $orderInfo['delivery_postcode'];

		//$orderAmount = currency($orderInfo['pay_amount'], null, false); //金额
		$orderAmount = $orderInfo['pay_amount']; //金额
    
    $orderCurrency = $orderInfo['currency']; //币种
	//$orderCurrency = isset($_SESSION['currency']) && $_SESSION['currency'] ? $_SESSION['currency'] : C('currency'); //币种
         
    //$returnUrl = url('payment/callback', array('pay' => 'visabill'));      //返回地址
    $returnUrl = "https://".$_SERVER['HTTP_HOST']."/payment/callback/pay/visabill";
	//$returnUrl = 'http://www.todudu.com/visabill_back.php';

    $remark = $orderInfo['order_sn'];               //备注 获取订单编号           


		$signsrc=$merNo.$gatewayNo.$orderNo.$orderCurrency.$orderAmount.$returnUrl.$signkey;   //校验源字符串

		$signInfo=strtoupper(hash("sha256",$signsrc));

         
		$button = '<form id="frm" action='.$gateway.' method="post" target="_self">'.
              "  <input type='hidden' name='merNo' value='". $merNo ."'>".
              "  <input type='hidden' name='gatewayNo' value='". $gatewayNo ."'>".
              "  <input type='hidden' name='orderCurrency' value='". $orderCurrency ."'>".
              "  <input type='hidden' name='orderNo' value='". $orderNo ."'>".
              "  <input type='hidden' name='orderAmount' value='". $orderAmount ."'>".
              "  <input type='hidden' name='returnUrl' value='". $returnUrl ."'>".
              "  <input type='hidden' name='signInfo' value='". $signInfo ."'>".
              "  <input type='hidden' name='remark' value='". $remark ."'>".
              "  <input type='hidden' name='firstName' value='".$firstName."'>".
              "  <input type='hidden' name='lastName' value='".$lastName."'>".
              "  <input type='hidden' name='email' value='".$email."'>".
              "  <input type='hidden' name='phone' value='".$phone."'>".
              "  <input type='hidden' name='language' value='".$language."'>";

		/* 支付方式为Credit Card */
		
		if ($paymentMethod=="Credit Card"){

			$button .= "  <input type='hidden' name='paymentMethod' value='".$paymentMethod."'>";
			$button .= "  <input type='hidden' name='country' value='".$country."'>";
			$button .= "  <input type='hidden' name='state' value='".$state."'>";
			$button .= "  <input type='hidden' name='city' value='".$city."'>";
			$button .= "  <input type='hidden' name='address' value='".$address."'>";
			$button .= "  <input type='hidden' name='zip' value='".$zip."'>";
		}

		$button .=" <input type='hidden' value='www.google.fr' name='sitename'>";
        $button .=" <input class='small_pay_button' type='submit' name='b1' value='" . L('_PAY_NOW_') . "'>".
                    "</form>";

        return $button;
  }
  
 	 private function checkGet()
  {
    $MerNo = $this->_paymentInfo['config']['MerNo'];                  //商户号

		$Signkey = $this->_paymentInfo['config']['Signkey'];              //Signkey私钥
        $GatewayNo = $this->_paymentInfo['config']['GatewayNo'];          //网关接入号
		

        $orderNo = $_REQUEST["orderNo"];             //订单号

        $orderCurrency = $_REQUEST["orderCurrency"]; //币种 

        $orderAmount = $_REQUEST["orderAmount"];     //金额

        $orderStatus = $_REQUEST["orderStatus"];     //支付状态

		$authTypeStatus = $_REQUEST["authTypeStatus"];	 //预授权情况

		$riskInfo = $_REQUEST["riskInfo"];			 //风控信息		//2012-12-25添加

        $orderInfo = $_REQUEST["orderInfo"];         //取得的交易结果信息

        $signInfo = $_REQUEST["signInfo"];           //取得的数据签名

			if (ctype_alnum($_REQUEST["tradeNo"])) { //支付平台流水号
				$tradeNo = $_REQUEST["tradeNo"];
			}else {
				$tradeNo = '';
			}		
	
	    $signsrc = $MerNo.$GatewayNo.$tradeNo.$orderNo.$orderCurrency.$orderAmount.$orderStatus.$orderInfo.$Signkey; //校验源字符串
		$checksignInfo=strtoupper(hash("sha256",$signsrc));      //signkey sha256加密

  
        
        /* 验证 */

       if ($signInfo == $checksignInfo){
				if ($orderStatus == '1')   //交易状态:成功
	 			{
					Log::write('pay log:orderStatus001');
					return true;
				}elseif ($orderStatus == '-1' || $orderStatus == '-2')   //交易状态:待处理，待确认    
				{
					Log::write('pay log:orderStatus002');
					return true;
				}else
				{
					Log::write('pay log:orderStatus003');
					return false;
				}
       }
	   else
	   {
		   Log::write('pay log:验证签名失败');
			return false;
	   }
  }

	public function callback()
	{
		if ($this->checkGet()) {
			Log::write('pay log:checkGet成功');
			$result = array(
				'verified' => true,
				'paidAmount' => $_REQUEST["orderAmount"],
				'paymentId' => $_REQUEST['tradeNo'],
				'orderNumber' => $_REQUEST["orderNo"],
				'updateOrderStatus' => false,
				'message' => '',
				'currency' => $_REQUEST["orderCurrency"],
			);
		} else {
			$result = array(
				'paymentId' => $_REQUEST['tradeNo'],
				'orderNumber' => $_REQUEST["orderNo"],
				'verified' => false,
			);
		}
		$orderStatus = $_REQUEST["orderStatus"];
		Log::write('pay log:visabill返回状态'.$orderStatus);
		if($orderStatus == '1' || $orderStatus == '-1' || $orderStatus == '-2'){
			$result['updateOrderStatus'] = true;
			$result['message'] = L('_PAYMENT_SUCCESS_');
		} else {
			$result['message'] = L('_PAYMENT_FAILURE_');
		}
		$result['returnMsg'] = $_REQUEST["orderInfo"];

		return $result;
	}

}
